import 'dart:async';
import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/regist/bean/message_code.dart';
import 'package:flutter_ahj_app/app/regist/viewmodel/RegistViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/flutter_AMapLocation_map.dart';
import 'package:flutter_ahj_app/base/cunchu/Constant.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/permissionGroup.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';
import 'InputView.dart';

import 'package:permission_handler/permission_handler.dart';
class RegisteredView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return _RegisteredViewState();
  }
}

class _RegisteredViewState extends BaseState<RegistViewModel, RegisteredView> {
  ///手机号码
  TextEditingController _phoneNumber = TextEditingController();
  FocusNode _phoneNumberFocusNode = FocusNode();

  ///验证码
  TextEditingController _yzmNumber = TextEditingController();

  ///设置密码
  TextEditingController _setPWD = TextEditingController();

  ///确认密码
  TextEditingController _confirmPWD = TextEditingController();
  FocusNode _confirmPWDrFocusNode = FocusNode();

  ///手机号 错误提示
  String _phoneErrorLable;

  ///确认密码 错误 提示
  String _confirmPWDLable;

  String _checkText = "获取验证码";
  Timer countDownTimer; //获取验证码计时器

  Widget _rbGetCheck;
  Widget _textfild;
  String isRequest = "0";

  AMapLocation location;

  bool isLoad = false;

  bool _isCheckXY = false;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      _getLocation();
    });
  }

  ///contentView
  _contentView(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Container(height: Dimens.dimens32),
          TopView(),
          Padding(
            padding: const EdgeInsets.only(bottom: 5),
            child: InputView(
                labelText: "手机号码",
                textEditingController: _phoneNumber,
                errorText: _phoneErrorLable,
                keyboardType: TextInputType.phone,
                focusNode: _phoneNumberFocusNode,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(11),
                ]),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: _textfild,
                ),
                Container(width: Dimens.dimens32),
                Expanded(
                  child: _rbGetCheck,
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 5),
            child: InputView(
              labelText: "设置密码",
              textEditingController: _setPWD,
              obscureText: true,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 5),
            child: InputView(
                labelText: "确认密码",
                textEditingController: _confirmPWD,
                errorText: _confirmPWDLable,
                obscureText: true,
                otherTextEditingController: _setPWD,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(11),
                  // WhitelistingTextInputFormatter(RegExp("[0-9]|[a-z]|[A-Z]")),
                ]),
          ),
          Padding(
            padding: EdgeInsets.only(top: Dimens.dimens16),
            child: _registBtn(),
          ),
            new Container(
            child: Padding(
              padding: EdgeInsets.only(top: Dimens.dimens20),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  InkWell(
                    onTap: () {
                      setState(() {
                        _isCheckXY = !_isCheckXY;
                      });
                    },
                    child: Image.asset(
                      _isCheckXY ? "img/xieyi_xz.png" : "img/xieyi_wxz.png",
                      width: Dimens.dimens20,
                      height: Dimens.dimens20,
                    ),
                  ),
                  Expanded(
                    child: RichText(
                      maxLines: 2,
                      text: TextSpan(
                        text: '  我已阅读并同意',
                        style: TextStyle(
                          color: SQColor.white,
                          fontSize: Dimens.dimens14,
                        ),
                        children: <TextSpan>[
                          TextSpan(
                            recognizer: TapGestureRecognizer()
                              ..onTap = (){
                                
                                Navigator.pushNamed(context, "/PTXYView",arguments: '1');
                              },
                            text: '《平台协议》',
                            style: TextStyle(
                                color: SQColor.secondary1,
                                fontSize: Dimens.dimens14,
                                fontWeight: FontWeight.bold),
                          ),
                          TextSpan(
                            text: '和',
                            style: TextStyle(
                                color: SQColor.white,
                                fontSize: Dimens.dimens14),
                          ),
                          TextSpan(
                            text: '《自雇者承揽协议》',
                            recognizer: TapGestureRecognizer()
                              ..onTap =(){
                                Navigator.pushNamed(context, "/PTXYView",arguments: '2');
                              },
                            style: TextStyle(
                                color: SQColor.secondary1,
                                fontSize: Dimens.dimens14,
                                fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///注册按钮
  _registBtn() {
    return RaisedButton(
      child: new Container(
        alignment: Alignment.center,
        height: 48,
        child: isRequest == "1"
            ? CircularProgressIndicator()
            : new Text(
                "注册",
                style: new TextStyle(
                  color: Colors.white,
                ),
              ),
      ),
      color: SQColor.secondary1,
      disabledColor: SQColor.secondary1,
      textColor: Colors.white,
      onPressed: () {
        _registerAction();
      },
    );
  }

  ///注册
  _registerAction() {
    if (_judge()) {
      return;
    }
    if (_setPWD.text != _confirmPWD.text) {
      setState(() {
        _confirmPWDLable = "您两次输入的密码不一致";
      });
      return;
    } else {
      setState(() {
        _confirmPWDLable = null;
      });
    }
    setState(() {
      isRequest = "1";
    });

    viewModel.userCheckCode(_phoneNumber.text, _yzmNumber.text);

    Stream<MessageCode> messageCheckCode = viewModel.getCodeCheckDataStream();

    messageCheckCode.listen((messageCheckCode) {
      if (messageCheckCode.code == 0 && messageCheckCode != null) {
        viewModel.setRegistData(_phoneNumber.text, _setPWD.text, _setPWD.text,
            _setPWD.text, _setPWD.text, _setPWD.text, _setPWD.text, _setPWD.text);

        Stream<MessageCode> registDataMessage = viewModel.getRegistDataStream();

        registDataMessage.listen((messageCheckCode) {
          if (messageCheckCode.code == 0 && messageCheckCode != null) {
            ToastUtils.showToast("注册成功");
            Navigator.pop(context);
          } else if (messageCheckCode.code == 1 && messageCheckCode != null) {
            ToastUtils.showToast(messageCheckCode.msg);
            isRequest = "0";
            setState(() {});
          } else {
            ToastUtils.showToast("注册失败");
            isRequest = "0";
            setState(() {});
          }
        });
      } else {
        ToastUtils.showToast(messageCheckCode.msg);
        isRequest = "0";
        setState(() {});
      }
    });

    /* HttpUtils.httpGet(HttpConst.checkCheckCode, data, (result) {
      // StringData dataRes = StringData.fromJson(json.decode(result));
      // 验证验证码成功
      // ToastUtils.showToast(dataRes.msg);

      HttpUtils.httpPostJsonWithOutToken(HttpConst.registerData, registerData, (result) {
      StringData dataRes = StringData.fromJson(json.decode(result));

      // 注册成功
      ToastUtils.showToast(dataRes.msg);
      Navigator.push(context, MaterialPageRoute(builder: (context) => AQBLogInPage()));
    }, context: context);

    }, context: context);*/
  }

  ///点击注册 判断
  bool _judge() {
    if (isEmpty(_phoneNumber.text)) {
      ToastUtils.showToast("手机号码不能为空");
      return true;
    } if (!_isCheckXY) {
      ToastUtils.showToast("请先同意协议");
      return true;
    }
    if (isEmpty(_yzmNumber.text)) {
      ToastUtils.showToast("验证码不能为空");
      return true;
    }
    if (isEmpty(_setPWD.text)) {
      ToastUtils.showToast("设置密码不能为空");
      return true;
    } else {
      if (6 > _setPWD.text.length) {
        ToastUtils.showToast("密码不能少于6位");
        return true;
      } else if (_setPWD.text.length > 12) {
        ToastUtils.showToast("密码不能大于12位");
        return true;
      }
    }
    if (isEmpty(_confirmPWD.text)) {
      ToastUtils.showToast("确认密码不能为空");
      return true;
    }
    if ("1" == isRequest) {
      //正在请求
      return true;
    }

    return false;
  }

  // 获取验证码
  _getCheckCode() {
    ///判断手机号
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    bool matched = exp.hasMatch(_phoneNumber.text);
    if (!matched) {
      setState(() {
        _phoneErrorLable = "请输入正确格式的手机号";
      });
      return;
    }

    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    setState(() {
      _checkText = "60秒";
    });
    countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          _checkText = "${60 - t.tick}秒";
        } else {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });

    viewModel.getCheckData(_phoneNumber.text);
    Stream<MessageCode> messageCode = viewModel.getDataStream();
    messageCode.listen((messageCode) {
      if (messageCode.code == 0 && messageCode != null) {
        ToastUtils.showToast(messageCode.msg);
      } else {
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      }
    });
  }

  @override
  Widget initWidget() {
    _rbGetCheck = Container(
      padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: RaisedButton(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens8))),
        child: new Container(
          alignment: Alignment.center,
          child: Text(
            _checkText,
            maxLines: 1,
            style: new TextStyle(fontSize: Dimens.textSize28),
          ),
        ),
        color: SQColor.secondary1,
        textColor: SQColor.white,
        disabledColor: SQColor.per12Black,
        disabledTextColor: SQColor.white,
        onPressed: _checkText == "获取验证码" ? () => _getCheckCode() : null,
      ),
    );

    _textfild = TextField(
        keyboardType: TextInputType.phone,
        controller: _yzmNumber,
        decoration: InputDecoration(
          labelText: "输入验证码",
          labelStyle: new TextStyle(color: Colors.white54),
          hintStyle: new TextStyle(color: Colors.white70),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: Colors.white30,
              width: 0.5,
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
            color: Colors.white,
            width: 1,
          )),
        ),
        style: new TextStyle(color: SQColor.white),
        cursorColor: SQColor.white,
        onChanged: (String str) {},
        inputFormatters: [
          LengthLimitingTextInputFormatter(11),
          // WhitelistingTextInputFormatter(RegExp("[0-9]")),
        ]);
    return Scaffold(
      appBar: MTopBar(title: "用户注册", elevation: 0).create(),
      backgroundColor: SQColor.theme_color,
      resizeToAvoidBottomInset: true,
      body: isLoad
          ? Container(
//        height: MediaQuery.of(context).size.height,
              padding:
                  EdgeInsets.fromLTRB(Dimens.dimens48, 0, Dimens.dimens48, 0),
              /* decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("img/login_bg.png"),
            fit: BoxFit.cover,
          ),
        ),*/
              child: _contentView(context),
            )
          : LoadingWidget(),
    );
  }

  _getLocation() async {
    String resultStr =
        await PerUtils.checkPermission(context, [Permission.location]);
    if (resultStr == '1') {
      location = await FlutterAMapLocation.getCurrentLocation();
    } else {
      location = null;
      setState(() {
        isLoad = true;
      });
      return;
    }

  }

}

///上方图片
class TopView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(
              "img/login_logo.png",
              width: Dimens.dimens64,
              height: Dimens.dimens64,
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Container(
              margin: EdgeInsets.fromLTRB(0, 16, 0, 16),
              child: Text(
                "欢迎注册青柠",
                style: TextStyle(
                    fontSize: Dimens.textSize16,
                    fontWeight: FontWeight.bold,
                    color: SQColor.white),
              ),
            ),
          ],
        ),
      ],
    );
  }
}
